package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetMealDao;
import com.itheima.domain.CheckGroup;
import com.itheima.domain.CheckItem;
import com.itheima.domain.Setmeal;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service(interfaceClass = SetMealService.class)
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private OrderDao orderDao;

    @Value("${out_put_path}")
    private String outputPath;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void add(Integer[] checkGroupIds, Setmeal setmeal) {
        //System.out.println("进入方法");
        setMealDao.add(setmeal);
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            setSetMealAndCheckGroup(setmeal.getId(), checkGroupIds);
        }


        //将图片名保存到redis
        System.out.println("保存套餐到数据库时访问redis");
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());


        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //生成静态页面的方法
    private void generateMobileStaticHtml() {
        //先把所有套餐的集合查出来
        List<Setmeal> setMealList = this.findAll();
        //生成套餐列表静态页面
        generateMobileSetMealListHtml(setMealList);
        //生成套餐详情静态页面
        generateMobileSetMealDetailHtml(setMealList);
    }

    //生成套餐列表静态页面的方法
    private void generateMobileSetMealListHtml(List<Setmeal> setMealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setMealList", setMealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }


    //生成套餐详情静态页面(多个)的方法
    private void generateMobileSetMealDetailHtml(List<Setmeal> setMealList) {
        for (Setmeal setmeal : setMealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", this.findSelMealsById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer writer = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File file = new File(outputPath + "\\" + htmlPageName);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            template.process(dataMap, writer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用PageHelper进行分页查询
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.selectByCondition(queryString);

        //将Page对象转换为PageResult对象
        return new PageResult(page.getTotal(), page.getResult());
    }


    private void setSetMealAndCheckGroup(Integer id, Integer[] checkGroupIds) {
        for (Integer checkGroupId : checkGroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkGroupId);
            setMealDao.setSetMealAndCheckGroup(map);
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    //查询带有详细信息的套餐数据
    @Override
    public Setmeal findSelMealsById(int id) {
        /*List<Setmeal> setMealList = setMealDao.findAll();
        for (Setmeal setmeal : setMealList) {
            List<CheckGroup> checkGroupList = setMealDao.findAllCheckGroupsBySid(id);
            for (CheckGroup checkGroup : checkGroupList) {
                List<CheckItem> checkItemList = checkGroupDao.findAllCheckItemsByCgId(checkGroup.getId());
                checkGroup.setCheckItems(checkItemList);
            }
            setmeal.setCheckGroups(checkGroupList);
        }*/

        Setmeal setmeal = setMealDao.findSetMealById(id);
        List<CheckGroup> checkGroupList = setMealDao.findAllCheckGroupsBySid(id);
        for (CheckGroup checkGroup : checkGroupList) {
            List<CheckItem> checkItemList = checkGroupDao.findAllCheckItemsByCgId(checkGroup.getId());
            checkGroup.setCheckItems(checkItemList);
        }
        setmeal.setCheckGroups(checkGroupList);
        return setmeal;
    }

    //饼图
    @Override
    public List<String> findAllSetMealNames() {

        List<Map<String, Object>> orderData = this.findOrderData();
        List<String> result = new ArrayList<>();
        for (Map<String, Object> map : orderData) {
            result.add((String) map.get("name"));
        }//这个方法后续可以使用链式编程风格改进一下
        return result;
    }

    //饼图
    @Override
    public List<Map<String, Object>> findOrderData() {
        return orderDao.findSetMealNameAndCount();
    }
}
